package com.nurt.dao.impl;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import com.nurt.dao.DishDao;
import com.nurt.entity.DishEntity;
import com.nurt.utils.DatabaseManager;

public class DishDaoImpl implements DishDao{
    private Connection conn;

    public DishDaoImpl() {
        try {
            this.conn = DatabaseManager.getInstance().getConnection();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    public List<DishEntity> selectDishes() throws SQLException {
        String sql = "SELECT * FROM dishes";
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        List<DishEntity> dishes = new ArrayList<>();
        while (rs.next()) {
            DishEntity dish = new DishEntity();
            dish.setDishId(rs.getInt("dishId"));
            dish.setName(rs.getString("name"));
            dish.setDescription(rs.getString("description"));
            dish.setImage(rs.getString("image"));
            dish.setPrice(rs.getDouble("price"));
            dishes.add(dish);
        }
        return dishes;
    }

    public DishEntity selectDish(int dishId) throws SQLException {
        String sql = "SELECT * FROM dishes WHERE dishId = " + dishId;
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        if (rs.next()) {
            DishEntity dish = new DishEntity();
            dish.setDishId(rs.getInt("dishId"));
            dish.setName(rs.getString("name"));
            dish.setDescription(rs.getString("description"));
            dish.setImage(rs.getString("image"));
            dish.setPrice(rs.getDouble("price"));
            return dish;
        } else {
            return null;
        }
    }

    public DishEntity selectDish(DishEntity dish) throws SQLException {
        return selectDish(dish.getDishId());
    }

    public int updateDish(DishEntity dish) throws SQLException {
        String sql = "UPDATE dishes SET name = '" + dish.getName() + "', description = '" + dish.getDescription() + "', image = '" + dish.getImage() + "', price = " + dish.getPrice() + " WHERE dishId = " + dish.getDishId();
        Statement stmt = conn.createStatement();
        return stmt.executeUpdate(sql);
    }

    public int insertDish(DishEntity dish) throws SQLException {
        String sql = "INSERT INTO dishes (name, description, image, price) VALUES ('" + dish.getName() + "', '" + dish.getDescription() + "', '" + dish.getImage() + "', " + dish.getPrice() + ")";
        Statement stmt = conn.createStatement();
        stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
        ResultSet rs = stmt.getGeneratedKeys();
        if (rs.next()) {
            return rs.getInt(1);
        } else {
            throw new SQLException("Creating dish failed, no ID obtained.");
        }
    }
}